<template>
	<view class="container">
		<!-- 导航栏，显示“计划”标题 -->
		<Navbar title="PLAN" />
		<view class="plan">
			<!-- 计划标题区域，包含计划图标 -->
			<view class="plan-title">
				<image src="/static/imgs/plan/plan.png"></image>
			</view>
			<!-- 计划内容区域 -->
			<view class="plan-box">
				<!-- 显示周计划组件，并在周计划改变时触发changeDay事件 -->
				<Week @change="changeDay" />
				<!-- 计划滚动区域，包含日常任务和日程事务 -->
				<view class="plan-scroll">
					<!-- 日常任务卡片，点击“+”可添加每日任务 -->
					<view class="plan-card">
						<view class="plan-card-title" @click="addDaily">Add your daily task +</view>
						<!-- 以列表形式显示每日计划，每个计划可勾选 -->
						<view class="plan-card-list">
							<view v-for="item in dailyPlan" :key="item.planId" class="day-plan" :class="{ checked: item.checked }">
								<view class="day-plan-radio" @click="changeChecked(item, 'task')"> </view>
								<view class="day-plan-text">
									{{ item.planName }}
								</view>
							</view>
						</view>
					</view>
					<!-- 日程事务卡片，点击“+”可添加日程事务 -->
					<view class="plan-card">
						<view class="plan-card-title" @click="addMatter">Add your days matter +</view>
						<!-- 以列表形式显示进行中的事务，每个事务显示进度和剩余天数 -->
						<view class="plan-card-list">
							<view class="matter-plan">
								<view class="matter-plan-type"> 进行中（{{ matterPlan.length }}） </view>
								<!-- 遍历dayPlans显示每个事务的详细信息，包括勾选状态、事务名称和剩余时间 -->
								<view class="matter-plan-card" v-for="item in matterPlan" :key="item.planId">
									<view class="matter-info">
										<view class="day-plan" :class="{ checked: item.checked }">
											<view class="day-plan-radio" @click="changeChecked(item, 'matter')"></view>
											<view class="day-plan-text">
												{{ item.planName }}
											</view>
										</view>
										<view class="matter-time">
											{{ formatTime(item.planTime) }}
										</view>
									</view>
									<view class="matter-days">
										<text>{{ calculateNumberOfDays(item.planTime) }}</text>
										<text>days left</text>
									</view>
								</view>
							</view>
							<!-- 		<view class="matter-plan">
								<view class="matter-plan-type"> 进行中（1） </view> -->
							<!-- 遍历dayPlans显示每个事务的详细信息，包括勾选状态、事务名称和剩余时间 -->
							<!-- <view class="matter-plan-card" v-for="item in dayPlans" :key="item.id">
									<view class="matter-info">
										<view class="day-plan" :class="{ checked: item.checked }">
											<view class="day-plan-radio" @click="changeChecked(item)"></view>
											<view class="day-plan-text">
												{{ item.text }}
											</view>
										</view>
										<view class="matter-time">
											{{ item.time }}
										</view>
									</view>
									<view class="matter-days">
										<text>{{ calculateNumberOfDays(item.time) }}</text>
										<text>days left</text>
									</view>
								</view> -->
							<!-- </view> -->
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
	<!-- daily输入框 -->
	<uni-popup ref="dailyPopup">
		<view class="popup-content">
			<view class="title">Add your daily task</view>
			<view class="input">
				<input class="uni-input" v-model="daily" placeholder="Daily Task" />
			</view>
			<view class="create-btn">
				<button size="mini" @click="saveDaily">Save</button>
				<button size="mini" @click="cancelDaily">Cancel</button>
			</view>
		</view>
	</uni-popup>
	<!-- matter 输入框 -->
	<uni-popup ref="matterPopup">
		<view class="popup-content">
			<view class="title">Add your days matter</view>
			<view class="input">
				<input class="uni-input" v-model="matter" placeholder="Days Matter" />
			</view>
			<view class="input">
				<picker mode="date" :value="matterDay" @change="bindDateChange">
					<view class="uni-input" style="color: gray">{{ matterDay }}</view>
				</picker>
			</view>
			<view class="create-btn">
				<button size="mini" @click="saveMatter">Save</button>
				<button size="mini" @click="cancelMatter">Cancel</button>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	// 导入组件和库
	import Navbar from '@/components/Navbar/Navbar.vue'; // 导入导航栏组件
	import Week from './week/index.vue'; // 导入周视图组件
	import dayjs from 'dayjs'; // 导入日期处理库
	import { ref, onMounted } from 'vue'; // 导入响应式引用
	import { addPlan, delPlan, getTask } from '@/api/plan';

	const dailyPopup = ref(); // 日常弹窗引用
	const matterPopup = ref(); // 事务弹窗引用
	const daily = ref(); // 日常输入
	const matter = ref(); // 事务输入
	const matterDay = ref(); // 事务日期输入
	const dailyPlan = ref([]); // 日常计划列表
	const matterPlan = ref([]); // 事务计划列表
	const currentDay = ref(); // 当前选择的日期

	/**
	 * 切换计划的选中状态
	 * @param {Object} plan - 要切换的计划对象
	 */
	const changeChecked = (plan, type) => {
		plan.checked = !plan.checked;
		delPlan(plan.planId).then((res) => {
			if (res.code == 200 && type == 'matter') {
				const index = matterPlan.value.findIndex((item) => item.planId == plan.planId);
				if (index >= 0) matterPlan.value.splice(index, 1);
			}
		});
	};

	/**
	 * 计算两个日期之间的天数差
	 * @param {String} time - 结束时间的字符串表示
	 * @returns {Number} 两个日期之间的天数差
	 */
	const calculateNumberOfDays = (time) => {
		const start = dayjs(); // 当前时间
		const end = dayjs(time); // 结束时间
		return end.diff(start, 'day') + 1;
	};

	/**
	 * 处理日期切换逻辑
	 * @param {String} day - 选中的日期
	 */
	const changeDay = (day) => {
		console.log('day-->', day);
		currentDay.value = day;
		getDaily(currentDay.value);
	};

	// 处理日常添加逻辑
	const addDaily = () => {
		dailyPopup.value.open('center');
	};

	const saveDaily = () => {
		const day = dayjs(currentDay.value).format('YYYY-MM-DD hh:mm:ss');
		addPlan(daily.value, 'task', day)
			.then((res) => {
				getDaily(currentDay.value);
			})
			.finally(() => {
				cancelDaily();
			});
	};

	const cancelDaily = () => {
		dailyPopup.value.close();
		daily.value = '';
	};

	// 处理事务添加逻辑
	const addMatter = () => {
		matterPopup.value.open('center');
	};

	const saveMatter = () => {
		const day = dayjs(matterDay.value).format('YYYY-MM-DD hh:mm:ss');
		addPlan(matter.value, 'matter', day)
			.then((res) => {
				getMatter();
			})
			.finally(() => {
				cancelMatter();
			});
	};

	const cancelMatter = () => {
		matterPopup.value.close();
		matter.value = '';
		matterDay.value = formatTime(new Date());
	};

	// 获取日常任务
	const getDaily = (time) => {
		getTask('task', time).then((res) => {
			console.log('matter --> res', res);
			dailyPlan.value = res.rows || [];
		});
	};

	// 获取事务任务
	const getMatter = () => {
		getTask('matter').then((res) => {
			console.log('matter --> res', res);
			matterPlan.value = res.rows || [];
		});
	};

	// 格式化时间
	const formatTime = (time) => {
		return dayjs(time).format('YYYY-MM-DD');
	};

	// 日期选择变更处理器
	const bindDateChange = (e) => {
		matterDay.value = e.detail.value;
	};

	// 组件挂载时初始化
	onMounted(() => {
		matterDay.value = currentDay.value = formatTime(new Date());
		getDaily(currentDay.value);
		getMatter();
	});
</script>

<style lang="scss" scoped>
	@import './plan.scss';

	::deep(.uni-popup__wrapper) {
		width: 100%;
	}
</style>
